/*
 * @Autor: lycheng
 * @Date: 2020-01-07 08:51:50
 */

(function () {
  // 接收主线程的 Float32Array 音频数据
  self.onmessage = function (e) {
    transAudioData.transcode(e.data);
  };

  const transAudioData = {
    /**
     * 总处理函数：降采样 + 转换为 16bit PCM
     */
    transcode(audioData) {
      let output = this.to16kHz(audioData);        // 降采样到 16kHz
      output = this.to16BitPCM(output);            // 转换为 16bit PCM
      output = Array.from(new Uint8Array(output.buffer)); // 转成普通数组
      self.postMessage(output); // 发送回主线程
    },

    /**
     * 将 44.1kHz 音频数据重采样为 16kHz
     */
    to16kHz(audioData) {
      const data = new Float32Array(audioData);
      const fitCount = Math.round(data.length * (16000 / 44100));
      const newData = new Float32Array(fitCount);
      const springFactor = (data.length - 1) / (fitCount - 1);

      newData[0] = data[0];
      for (let i = 1; i < fitCount - 1; i++) {
        const tmp = i * springFactor;
        const before = Math.floor(tmp);
        const after = Math.ceil(tmp);
        const atPoint = tmp - before;
        newData[i] = data[before] + (data[after] - data[before]) * atPoint;
      }
      newData[fitCount - 1] = data[data.length - 1];
      return newData;
    },

    /**
     * 将 float [-1, 1] 转换为 int16 PCM
     */
    to16BitPCM(input) {
      const dataLength = input.length * 2;
      const dataBuffer = new ArrayBuffer(dataLength);
      const dataView = new DataView(dataBuffer);

      let offset = 0;
      for (let i = 0; i < input.length; i++, offset += 2) {
        let s = Math.max(-1, Math.min(1, input[i]));
        dataView.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true); // 小端
      }

      return dataView;
    },
  };
})();